<template>
  <div>
    <p>
      直播位置：<span>{{ props.position || '--' }}</span>
    </p>

    <div id="video_wrap" class="video-js" v-if="!isError">
      <div class="ex12313123123"></div>
      <video
        id="video video-js"
        ref="videoPlayer"
        preload="auto"
        playsinline="true"
        x-webkit-airplay="true"
        webkit-playsinline="true"
        x5-video-player-type="h5"
        x-video-orientation="h5"
        x5-video-player-fullscreen="true"
        muted="false"
      >
        <source
          :src="videoUrl"
          type="video/mp4"
        />
      </video>
      <!-- <canvas ref="canvas" id="canvas"></canvas> -->
    </div>
    <div class="video-js holder" v-else>
      {{ errorText }}
    </div>
  </div>
</template>

<script setup>
  import { onMounted, ref, onUnmounted, nextTick, computed } from 'vue';
  import { getDeviceVideo } from '@/api/map';
  import flvjs from "flv.js";
  const videoPlayer = ref();
  const props = defineProps({
    position: {
      default() {
        return '--';
      },
    },
    deviceId: {
      required: true,
    },
  });
  const videoUrl = ref('');
  const isError = ref(false);
  const errorText = ref('');
  const isSupportFlv = computed (() => {
    return !!window.MediaSource
  })

  onMounted(async () => {
    try {
      const res = await getDeviceVideo(props.deviceId);
      if (isSupportFlv.value) {
        videoUrl.value = res.data.url;
        var flvPlayer = flvjs.createPlayer({
            type: 'flv',
            url: videoUrl.value
        });
        flvPlayer.attachMediaElement(videoPlayer.value);
        flvPlayer.load();
        flvPlayer.play();
      } else if (!res.data.hlsHd) {
        isError.value = true;
        errorText.value = '暂无可用流';
      } else {
        videoUrl.value = res.data.hlsHd;
      }
      videoPlayer.value.play();
    } catch (error) {
      console.error(error);
    }
  });
</script>

<style lang="scss" scoped>
  .video-js {
    height: 4rem;
    width: 100%;
    margin-bottom: 1.22rem;
    position: relative;
    background-color: #000;
  }

  p {
    font-size: 0.28rem;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    color: #7e7e7e;
    line-height: 0.4rem;
    margin-bottom: 0.47rem;

    span {
      color: #1e1e1e;
    }
  }
  .holder {
    font-size: 0.32rem;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  video {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    object-fit: fit;
  }
  canvas {
    height: 100%;
    width: 100%;
  }
</style>
